package com.LeeCode;

import java.util.ArrayList;
import java.util.List;

/**
 * 找到 K 个最接近的元素
 */

public class Code658 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int k = 4, x = 3;
        System.out.println(new Code658().findClosestElements1(arr, k, x));
    }

    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        int left = 0, right = arr.length - 1;
        while (left < right) {
            int tmpLeft = Math.abs(arr[left] - x);
            int tmpRight = Math.abs(arr[right] - x);

            if (right - left + 1 > k) {
                if (tmpLeft > tmpRight) {
                    left++;
                } else {
                    right--;
                }
            } else {
                break;
            }
        }
        List<Integer> ans = new ArrayList<>();
        for (int i = left; i <= right; i++) {
            ans.add(arr[i]);
        }

        return ans;
    }

    // 二分法
    public List<Integer> findClosestElements1(int[] arr, int k, int x) {
        // 找到 x 插入的位置（也可以理解为最接近 x 的位置）
        int left = 0, right = arr.length - k;

        while (left < right) {
            int mid = left + (right - left) / 2;

            // 比较 x 到 arr[mid] 和 arr[mid + k] 的距离
            if (x - arr[mid] > arr[mid + k] - x) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }


        List<Integer> result = new ArrayList<>();
        for (int i = left; i < left + k; i++) {
            result.add(arr[i]);
        }

        return result;
    }
}
